package lc2;
import java.util.*;
import org.junit.*;
public class Ex611 {
    class Solution {
        public int triangleNumber(int[] nums) {
            int n = nums.length, res = 0;
            Arrays.sort(nums);
            for (int i = 0; i < n - 2; i++) {
                if (nums[i] == 0) {
                    continue;
                }
                int last = i + 1;
                for (int j = i + 1; j < n - 1; j++) {
                    if (nums[j] == 0) {
                        continue;
                    }
                    int sum = nums[i] + nums[j];
                    int lo = last, hi = n - 1;
                    while (lo < hi) {
                        int m = (hi - lo + 1) / 2 + lo;
                        if (nums[m] >= sum) {
                            hi = m - 1;
                        } else {
                            lo = m;
                        }
                    }
                    if (nums[lo] < sum) {
                        res += lo - j;
                    } else {
                        break;
                    }
                    last = lo;
                }
            }
            return res;
        }
    }

    @Test
    public void test() {
        Solution s = new Solution();
        int[] nums = new int[]{2,2,3,4};
        System.out.println(s.triangleNumber(nums))        ;
    }
}
